/**
 * 2017年12月20日
 */
package com.cmwa.scbp.sys.msg.filter.filters;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cmwa.scbp.sys.msg.dao.IMsgSendDao;
import com.cmwa.scbp.sys.msg.filter.MsgFilter;
import com.cmwa.scbp.sys.msg.filter.MsgFilterChain;
import com.cmwa.scbp.sys.msg.filter.MsgFilterResult;
import com.cmwa.scbp.sys.msg.filter.enums.MsgFilterCodeEnum;
import com.cmwa.scbp.sys.msg.vo.ManualOperationParamsVo;
import com.cmwa.scbp.sys.msg.vo.MsgWaitSendVo;
import com.cmwa.scbp.utils.JsonUtil;

/**
 * @author ex-zuotc
 * 2017年12月20日
 */
@Component("msgTypeSendCountFilter")
public class MsgTypeSendCountFilter implements MsgFilter {
	
	private static Logger logger = LoggerFactory.getLogger(MsgTypeSendCountFilter.class);
	
	@Resource
	private IMsgSendDao iMsgSendDao;

	@Override
	@SuppressWarnings("unchecked")
	public void doFilter(List<MsgWaitSendVo> sendVos, ManualOperationParamsVo params, String filterParam, MsgFilterChain filterChian) {
		logger.error("sendVo:" + params.getMsgCode() + ", filterParam:" + filterParam);
		MsgFilterResult msgFilterResult = filterChian.getMsgFilterResult();
		
		if (StringUtils.isNotEmpty(filterParam)) {
			Map<String, Object> paramMap = JsonUtil.parseJson(filterParam, Map.class);
			// 多少分钟
			Integer minute = (Integer) paramMap.get("minute");
			// 发送数量
			Integer count = (Integer) paramMap.get("count");
			
			int sentCount = iMsgSendDao.getEmailTypeCount(params.getMsgCode(), minute);
			if (sentCount >= count) {
				msgFilterResult.setSendable(false);
				msgFilterResult.setFilterCode(MsgFilterCodeEnum.M008_3);
				msgFilterResult.setMessage("同一类型的邮件" + minute + "分钟内发送数量超过" + count + "封。");
				logger.error("sendVo:" + params.getMsgCode() + ", filterParam:" + filterParam + "，msgFilterResult" + msgFilterResult);
				return;
			}
		}
		
		// next
		filterChian.doFilter(sendVos, params);
	}

}
